use qrcode::QrCode;
use console::Term;
use dialoguer::{Input, Select, Confirm};
use std::process::{Command, exit};
use regex::Regex;
use crate::prompt_theme::MyTheme;
use std::env;
use winapi::um::winuser::{SW_SHOWNORMAL, SW_SHOW};
use crate::utils::{exec, clean_dir};
use image::Luma;
use winapi::um::shellapi::{SHERB_NOCONFIRMATION, SHERB_NOPROGRESSUI, SHERB_NOSOUND, SHEmptyRecycleBinW};
use std::ptr::{null_mut};
use winreg::RegKey;
use winapi::um::winreg::HKEY_CURRENT_USER;

pub struct Tools{}

impl Tools{
    /// run
    pub fn run(&self){
        let selections = &[
            "qrcode",
            "qrcode [不好用]",
            "wifi 密码",
            "重置winsock",
            "清理垃圾||使用痕迹"
        ];

        let selection = Select::with_theme(&MyTheme::custom())
            .with_prompt("请选择使用工具:")
            .items(&selections[..])
            .interact_opt()
            .unwrap();
        if let Some(selection) = selection {
            match selection {
                0 => self.qrcode_image(),
                1 => self.qrcode(),
                2 => self.show_current_wifi_password(),
                3 => self.reset_winsock(),
                4 => self.clean_disk(),
                _ => println!("没有匹配到 {} 或暂时不支持",selections[selection])
            }
        }else {
            println!("你没有选择任何选项")
        }
    }

    /// 二维码
    pub fn qrcode(&self) {
        // 提示输入
        let term = Term::buffered_stderr();

        let input: String = Input::new()
            .with_prompt("请输入二维码内容：").
            interact_on(&term)
            .unwrap();
        let code = QrCode::new(input).unwrap();
        let string = code.render::<char>()
            .quiet_zone(true)
            .module_dimensions(2, 1)
            .build();
        println!("{}", string);
    }

    /// 二维码 保存在 文件中 打开
    pub fn qrcode_image(&self) {
        // 提示输入
        let term = Term::buffered_stderr();

        let input: String = Input::new()
            .with_prompt("请输入二维码内容：").
            interact_on(&term)
            .unwrap();
        let code = QrCode::new(input).unwrap();
        let image = code.render::<Luma<u8>>().build();

        // Save the image.
        // 临时目录
        let mut tmp = env::temp_dir();
        tmp.push("qrcode.png");
        let tmp = tmp.to_str().unwrap();
        println!("tmp: {}",tmp);
        image.save(tmp).unwrap();

        // 打开
        exec("open",tmp,"",SW_SHOWNORMAL);

    }

    /// 查看当前 wifi 密码
    pub fn show_current_wifi_password(&self) {
        let output = Command::new("cmd.exe")
            .args(&["/C","chcp 437","&&"])
            .args(&["netsh","wlan","show","interfaces"])
            .output().unwrap();

        let cow =String::from_utf8_lossy(&output.stdout);

        let mut wifi_name = String::new();
        let split_regex = Regex::new(" SSID").unwrap();

        for line in cow.lines() {
            if split_regex.is_match(line) {
                wifi_name = line.split(":").nth(1).unwrap_or("").trim().to_string();
                break;
            }
        }

        if wifi_name.is_empty() {
            println!("没有找到当前连接wifi");
            exit(0);
        }
        println!("wifi name : {}",wifi_name);

        // 查找wifi 密码
        let name = format!("name={}",wifi_name);
        let output = Command::new("cmd.exe")
            .args(&["/C","chcp 437","&&"])
            .args(&["netsh","wlan","show","profile",&name,"key=clear"])
            .output().unwrap();

        let cow =String::from_utf8_lossy(&output.stdout);
        let mut wifi_password = String::new();
        let split_regex = Regex::new(" Key Content").unwrap();

        for line in cow.lines() {
            if split_regex.is_match(line) {
                wifi_password = line.split(":").nth(1).unwrap_or("").trim().to_string();
                break;
            }
        }
        if wifi_password.is_empty() {
            println!("没有找到当前连接wifi");
            exit(0);
        }

        println!("wifi password: {}",wifi_password);

        if Confirm::with_theme(&MyTheme::custom())
            .with_prompt("是否生成二维码？")
            .default(true)
            .interact()
            .unwrap(){

            let mut input = format!("WIFI:T:WPA;P:{};S:{};",wifi_password,wifi_name);
            // 判断是否为隐藏wifi
            if Confirm::with_theme(&MyTheme::custom())
                .with_prompt("是否是隐藏WIFI？")
                .default(false)
                .interact()
                .unwrap(){
                // 隐藏
                input.push_str("H:true;");
            }


            let code = QrCode::new(input).unwrap();
            let image = code.render::<Luma<u8>>().build();

            // Save the image.
            // 临时目录
            let mut tmp = env::temp_dir();
            tmp.push("wifi.png");
            let tmp = tmp.to_str().unwrap();
            image.save(tmp).unwrap();

            // 打开
            exec("open",tmp,"",SW_SHOWNORMAL);
        }
    }

    /// 重置winsock
    /// 执行命令： `netsh winsock reset`
    pub fn reset_winsock(&self) {
        exec("runas","netsh","winsock reset",SW_SHOW);
    }

    /// 清理垃圾
    fn clean_disk(&self) {
        println!("清理回收站.......");
        // 清空回收站
       let result = unsafe {
             SHEmptyRecycleBinW(
                null_mut(),
                null_mut(),
                SHERB_NOCONFIRMATION | SHERB_NOPROGRESSUI | SHERB_NOSOUND
            )
        };
        if result == 0 {
            println!("清理回收站 完成");
        }else {
            eprintln!("清理回收站 error 或 回收站为空");
        }

        // 清空最近使用文件
        println!("清理最近使用文件记录............");
        let appdata =env!("APPDATA");
        let _=clean_dir(format!("{}{}",appdata,"\\Microsoft\\Windows\\Recent"));
        println!("清理最近使用文件记录 完成");
        // 清理windows 搜索记录
        println!("删除Explorer 搜索记录.......");
        let explorer = RegKey::predef(HKEY_CURRENT_USER).open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer").unwrap();
        let _ =explorer.delete_subkey("WordWheelQuery");
        println!("删除Explorer 完成");
    }


}